using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class PlayerLevel : MonoBehaviour
{
    public UnityEvent OnPlayerUpGrade;
    [Header("----- Grade -----")]
    [SerializeField] private int _grade = 1;
    private float _currentGradeExp = 0;
    private float _currentGradeMaxExp;
    private Player_Stat _playerStat;

    private void Awake()
    {
        _playerStat = GetComponent<Player_Stat>();
    }
    private void OnEnable()
    {
        //绑定收集经验事件
        EventCenter.AddEventListener<float>(EventName.CollectExp, AddExp);
    }
    private void OnDisable()
    {
        //取消绑定收集经验事件
        EventCenter.RemoveEventListener<float>(EventName.CollectExp, AddExp);
    }

    private void Start()
    {
        _currentGradeMaxExp = _grade * 5;
        //更新经验条和等级
        EventCenter.TriggerEvent(EventName.UI_UpdateExpBar, _currentGradeExp, _currentGradeMaxExp, _grade);
    }

    //增加经验，敌人死亡时触发
    private void AddExp(float value)
    {
        _currentGradeMaxExp = _grade * 5;

        _currentGradeExp += value;

        if (_currentGradeExp >= _currentGradeMaxExp)
        {
            _currentGradeExp -= _currentGradeMaxExp;
            _grade++;

            OnPlayerUpGrade?.Invoke();
            
            AddStat();
        }

        _currentGradeMaxExp = _grade * 5;

        //更新经验条和等级
        EventCenter.TriggerEvent(EventName.UI_UpdateExpBar, _currentGradeExp, _currentGradeMaxExp, _grade);
    }
    
    private void AddStat()
    {
        _playerStat.AddMaxHealthStat(_grade);
        if (_grade != 1 && _grade % 2 != 0)
        {
            _playerStat.AddArmorStat(1);
            _playerStat.AddDamageBounsStat(.1f);
        }
    }
}
